﻿using MetroDataApi.Models;
using System.Collections.Generic;
using System.Web.Http;
using Newtonsoft.Json;
using System;


namespace MetroDataApi.Controllers
{
    public class RecentChangesController : ApiController
    {

        // GET api/recentchanges/5
        public string Get(int prjId, string type, string location, string time1 = "", string time2 = "",
            string fuzzy = "0", string isDesign = "false")
        {
            //验证日期格式是否正确
            DateTime temp;
            if (!DateTime.TryParse(time1, out temp) || !DateTime.TryParse(time2, out temp))
            {
                time1 = "";
                time2 = "";
                fuzzy = "0";
            }

            if (fuzzy == null) fuzzy = "0";
            if (isDesign == null) isDesign = "false";
            var changes = Recent2Changes.GetChanges(prjId, type, location, time1, time2, fuzzy, bool.Parse(isDesign));
            return JsonConvert.SerializeObject(changes, Formatting.None,
                new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore,
                    Converters = new List<JsonConverter> { new StandardFloatConverter() }
                });
        }

    }

    public class StandardFloatConverter : JsonConverter
    {
        public override bool CanRead
        {
            get
            {
                return false;
            }
        }
        public override bool CanWrite
        {
            get
            {
                return true;
            }
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
            {
                writer.WriteNull();
                return;
            }

            var val = Convert.ToDouble(value);
            if (Double.IsNaN(val) || Double.IsInfinity(val))
            {
                writer.WriteNull();
                return;
            }
            // Preserve the type, otherwise values such as 3.14f may suddenly be
            // printed as 3.1400001049041748.
            if (value is float)
                writer.WriteValue((float)value);
            else
                writer.WriteValue((double)value);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(double) || objectType == typeof(float);
        }
    }
}
